package com.zdp.oauth.entity.oauth;

import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <h1>oauth认证对象</h1>
 */
@Getter
@Setter
public class SignInIdentity implements UserDetails {

    // 主键
    private Integer id;
    // 用户名
    private String username;
    /**
     * 密码
     */
    private String password;
    // 昵称
    private String fullname;
    // 手机号
    private String mobile;
    // 角色
    private Set<String> roles;
    // 权限
    private Set<String> permissions;
    // 角色权限集合
    private List<GrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 如果该用户既分配角色没有任何权限默认给一个游客角色
        if (CollectionUtils.isEmpty(this.roles) && CollectionUtils.isEmpty(this.permissions)) {
            this.authorities = AuthorityUtils
                    .commaSeparatedStringToAuthorityList("ROLE_sightseer");
        } else {
            Set<String> resourcesAvailable = Stream.concat(this.roles.stream(), this.permissions.stream()).collect(Collectors.toSet());
            this.authorities = resourcesAvailable.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        }
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
